<template>
  <div class="p-6">
    <!-- Tab切换 -->
    <div class="glass-effect rounded-2xl p-2 mb-6 shadow-pink-md overflow-x-auto">
      <div class="flex gap-2 min-w-max">
        <div
          v-for="tab in tabs"
          :key="tab.key"
          class="py-3 px-4 rounded-xl text-center cursor-pointer transition-all duration-300 whitespace-nowrap"
          :class="
            activeTab === tab.key
              ? 'bg-gradient-to-r from-pink-400 to-pink-500 text-white shadow-pink-md'
              : 'text-pink-400 hover:bg-pink-50'
          "
          @click="activeTab = tab.key"
        >
          <span class="text-lg mr-1">{{ tab.icon }}</span>
          <span class="font-medium text-sm">{{ tab.label }}</span>
        </div>
      </div>
    </div>

    <!-- 漂流瓶 -->
    <div v-if="activeTab === 'bottles'" class="space-y-4">
      <!-- 添加按钮 -->
      <div class="flex justify-between items-center">
        <n-button type="primary" size="large" class="rounded-xl" @click="showBottleModal = true">
          + 写漂流瓶
        </n-button>
        <n-button size="large" class="rounded-xl" @click="randomBottle">
          🎲 随机一瓶
        </n-button>
      </div>

      <!-- 漂流瓶列表 -->
      <div class="space-y-4">
        <div
          v-for="bottle in bottles"
          :key="bottle.id"
          class="glass-effect rounded-3xl p-6 shadow-pink-xl relative"
        >
          <n-button
            size="tiny"
            tertiary
            type="error"
            class="absolute top-4 right-4"
            @click="handleDeleteBottle(bottle.id)"
          >
            删除
          </n-button>
          <div class="flex items-start gap-4 mb-4">
            <div class="text-4xl">{{ bottle.emoji }}</div>
            <div class="flex-1">
              <div class="flex items-center gap-2 mb-2">
                <span class="font-bold text-pink-600">{{ bottle.author }}</span>
                <span class="text-sm text-pink-400">{{ bottle.date }}</span>
              </div>
              <p class="text-pink-600 leading-relaxed">{{ bottle.content }}</p>
            </div>
          </div>
          <div v-if="bottle.image" class="rounded-2xl overflow-hidden">
            <img :src="bottle.image" class="w-full" alt="配图" />
          </div>
        </div>
      </div>
    </div>

    <!-- 照片墙 -->
    <div v-if="activeTab === 'photos'" class="space-y-4">
      <!-- 添加按钮 -->
      <div class="flex justify-end">
        <n-button type="primary" size="large" class="rounded-xl" @click="showPhotoModal = true">
          + 上传照片
        </n-button>
      </div>

      <!-- 照片网格 -->
      <n-image-group>
        <div class="grid grid-cols-2 gap-3">
          <div
            v-for="photo in photos"
            :key="photo.id"
            class="glass-effect rounded-2xl overflow-hidden shadow-pink-md transition-all duration-300 hover:scale-105"
          >
            <div class="aspect-square bg-pink-100 relative overflow-hidden cursor-pointer">
              <n-image
                :src="photo.url"
                :alt="photo.title"
                object-fit="cover"
                class="w-full h-full photo-image"
                :img-props="{ style: 'object-fit: cover; width: 100%; height: 100%;' }"
                @error="handleImageError"
              />
            </div>
            <div class="p-3 flex items-center justify-between">
              <div class="flex-1">
                <p class="text-sm text-pink-600 font-medium">{{ photo.title }}</p>
                <p class="text-xs text-pink-400 mt-1">{{ photo.date }}</p>
              </div>
              <n-button
                size="tiny"
                tertiary
                type="error"
                @click.stop="handleDeletePhoto(photo.id)"
              >
                删除
              </n-button>
            </div>
          </div>
        </div>
      </n-image-group>
    </div>

    <!-- 小纸条 -->
    <div v-if="activeTab === 'notes'" class="space-y-4">
      <!-- 输入框 -->
      <div class="glass-effect rounded-2xl p-4 shadow-pink-md">
        <n-input
          v-model:value="newNote"
          type="textarea"
          placeholder="给TA留个小纸条吧 💌"
          :rows="3"
          class="mb-3"
        />
        <n-button type="primary" size="large" block class="rounded-xl" @click="addNote">
          发送纸条
        </n-button>
      </div>

      <!-- 纸条列表 -->
      <div class="space-y-3">
        <div
          v-for="note in notes"
          :key="note.id"
          class="glass-effect rounded-2xl p-5 shadow-pink-md relative"
          :class="note.fromMe ? 'bg-pink-50/50' : ''"
        >
          <n-button
            size="tiny"
            tertiary
            type="error"
            class="absolute top-3 right-3"
            @click="handleDeleteNote(note.id)"
          >
            删除
          </n-button>
          <div class="flex items-start gap-3">
            <div class="text-3xl">{{ note.fromMe ? '💝' : '💌' }}</div>
            <div class="flex-1">
              <div class="flex items-center gap-2 mb-2">
                <span class="font-bold text-pink-600">{{ note.author }}</span>
                <span class="text-xs text-pink-400">{{ note.time }}</span>
              </div>
              <p class="text-pink-600">{{ note.content }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 打卡记录 -->
    <div v-if="activeTab === 'checkin'" class="space-y-4">
      <!-- 打卡统计 -->
      <div class="glass-effect rounded-3xl p-6 shadow-pink-xl text-center">
        <h3 class="text-xl font-bold text-pink-600 mb-4">连续打卡</h3>
        <div class="text-6xl font-bold text-pink-500 mb-2">{{ checkinStats.streak }}</div>
        <p class="text-pink-400">天</p>
      </div>

      <!-- 今日打卡 -->
      <div class="grid grid-cols-2 gap-4">
        <div
          class="glass-effect rounded-2xl p-6 text-center cursor-pointer transition-all duration-300 hover:scale-105"
          :class="todayCheckin.morning ? 'bg-pink-100/50' : ''"
          @click="handleCheckin('morning')"
        >
          <div class="text-5xl mb-3">🌅</div>
          <p class="font-bold text-pink-600">
            {{ todayCheckin.morning ? '已打卡 ✓' : '早安打卡' }}
          </p>
        </div>
        <div
          class="glass-effect rounded-2xl p-6 text-center cursor-pointer transition-all duration-300 hover:scale-105"
          :class="todayCheckin.evening ? 'bg-pink-100/50' : ''"
          @click="handleCheckin('evening')"
        >
          <div class="text-5xl mb-3">🌙</div>
          <p class="font-bold text-pink-600">
            {{ todayCheckin.evening ? '已打卡 ✓' : '晚安打卡' }}
          </p>
        </div>
      </div>

      <!-- 打卡历史 -->
      <div class="glass-effect rounded-2xl p-6 shadow-pink-md">
        <h3 class="text-lg font-bold text-pink-600 mb-4">打卡历史</h3>
        <div class="space-y-3">
          <div
            v-for="record in checkinHistory"
            :key="record.id"
            class="bg-white/50 rounded-xl p-4 flex items-center justify-between"
          >
            <div>
              <p class="font-medium text-pink-600">{{ record.date }}</p>
              <p class="text-sm text-pink-400 mt-1">{{ record.types }}</p>
            </div>
            <div class="text-2xl">{{ record.icon }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 情侣问答 -->
    <div v-if="activeTab === 'qa'" class="space-y-4">
      <!-- 添加问题按钮 -->
      <div class="flex justify-end">
        <n-button type="primary" size="large" class="rounded-xl" @click="showQAModal = true">
          + 添加问题
        </n-button>
      </div>

      <!-- 问答历史 -->
      <div class="glass-effect rounded-2xl p-6 shadow-pink-md">
        <h3 class="text-lg font-bold text-pink-600 mb-4">问答历史</h3>
        <div class="space-y-4">
          <div v-for="qa in qaHistory" :key="qa.id" class="bg-white/50 rounded-xl p-4">
            <div class="flex items-start justify-between mb-2">
              <p class="font-medium text-pink-600 flex-1">{{ qa.question }}</p>
              <n-button size="tiny" tertiary type="error" @click="handleDeleteQA(qa.id)">
                删除
              </n-button>
            </div>
            <div class="space-y-2 text-sm">
              <p class="text-pink-500">💝 你: {{ qa.myAnswer || '未回答' }}</p>
              <p class="text-pink-500">💌 TA: {{ qa.taAnswer || '未回答' }}</p>
            </div>
            <p class="text-xs text-pink-400 mt-2">{{ qa.date }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 书影音 -->
    <div v-if="activeTab === 'media'" class="space-y-4">
      <!-- 分类切换 -->
      <div class="glass-effect rounded-2xl p-2 shadow-pink-md">
        <div class="grid grid-cols-3 gap-2">
          <div
            v-for="type in mediaTypes"
            :key="type.key"
            class="py-2 px-3 rounded-xl text-center cursor-pointer transition-all duration-300"
            :class="
              selectedMediaType === type.key
                ? 'bg-gradient-to-r from-pink-400 to-pink-500 text-white'
                : 'text-pink-400'
            "
            @click="selectedMediaType = type.key"
          >
            <span class="text-xl">{{ type.icon }}</span>
            <span class="text-sm ml-1">{{ type.label }}</span>
          </div>
        </div>
      </div>

      <!-- 添加按钮 -->
      <div class="flex justify-end">
        <n-button type="primary" size="large" class="rounded-xl" @click="showMediaModal = true">
          + 添加推荐
        </n-button>
      </div>

      <!-- 媒体列表 -->
      <div class="space-y-3">
        <div
          v-for="item in filteredMedia"
          :key="item.id"
          class="glass-effect rounded-2xl p-5 shadow-pink-md flex items-start gap-4"
        >
          <div
            class="flex-shrink-0 w-16 h-16 bg-pink-100 rounded-xl flex items-center justify-center text-3xl"
          >
            {{ item.icon }}
          </div>
          <div class="flex-1">
            <h4 class="font-bold text-pink-600 mb-1">{{ item.title }}</h4>
            <p class="text-sm text-pink-400 mb-2">评分: {{ item.rating || '未评分' }}/10</p>
            <div class="flex items-center gap-2">
              <n-tag size="small" :bordered="false" type="info">
                {{ item.fromMe ? '我推荐' : 'TA推荐' }}
              </n-tag>
              <n-tag
                size="small"
                :bordered="false"
                :type="item.completed ? 'success' : 'warning'"
              >
                {{ item.completed ? '已看' : '想看' }}
              </n-tag>
            </div>
          </div>
          <n-button size="tiny" tertiary type="error" @click="handleDeleteMedia(item.id)">
            删除
          </n-button>
        </div>
      </div>
    </div>

    <!-- 回收站 -->
    <div v-if="activeTab === 'trash'" class="space-y-4">
      <div
        v-if="
          deletedBottles.length === 0 &&
          deletedPhotos.length === 0 &&
          deletedNotes.length === 0 &&
          deletedQAs.length === 0 &&
          deletedMedias.length === 0
        "
        class="text-center py-12"
      >
        <div class="text-8xl mb-4">🗑️</div>
        <p class="text-pink-400 text-lg">回收站是空的</p>
        <p class="text-pink-300 text-sm mt-2">已删除的内容会保留在这里</p>
      </div>

      <div v-else class="space-y-6">
        <!-- 漂流瓶回收站 -->
        <div v-if="deletedBottles.length > 0">
          <h3 class="text-lg font-bold text-pink-600 mb-3">漂流瓶</h3>
          <div class="space-y-3">
            <div
              v-for="bottle in deletedBottles"
              :key="bottle.id"
              class="glass-effect rounded-2xl p-5 shadow-pink-md opacity-50"
            >
              <div class="flex items-start gap-4">
                <div class="text-3xl grayscale">🎈</div>
                <div class="flex-1">
                  <div class="flex items-start justify-between mb-2">
                    <div>
                      <div class="flex items-center gap-2 mb-2">
                        <span class="font-bold text-pink-600 line-through">
                          {{ bottle.creator_id === userId ? '我' : 'TA' }}
                        </span>
                        <span class="text-sm text-pink-400">
                          {{ new Date(bottle.created_at).toLocaleDateString('zh-CN') }}
                        </span>
                      </div>
                      <p class="text-pink-600 line-through">{{ bottle.content }}</p>
                      <n-tag size="small" type="default" :bordered="false" class="mt-2">
                        已删除
                      </n-tag>
                    </div>
                    <div class="flex gap-2">
                      <n-button size="small" tertiary type="success" @click="handleRestoreBottle(bottle.id)">
                        恢复
                      </n-button>
                      <n-button size="small" tertiary type="error" @click="handlePermanentDeleteBottle(bottle.id)">
                        永久删除
                      </n-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 照片回收站 -->
        <div v-if="deletedPhotos.length > 0">
          <h3 class="text-lg font-bold text-pink-600 mb-3">照片墙</h3>
          <div class="space-y-3">
            <div
              v-for="photo in deletedPhotos"
              :key="photo.id"
              class="glass-effect rounded-2xl p-5 shadow-pink-md opacity-50"
            >
              <div class="flex items-start gap-4">
                <div class="text-3xl grayscale">📸</div>
                <div class="flex-1">
                  <div class="flex items-start justify-between mb-2">
                    <div>
                      <h4 class="text-lg font-bold text-pink-600 line-through">
                        {{ photo.description || '美好回忆' }}
                      </h4>
                      <p class="text-sm text-pink-400 mt-1">
                        📅 {{ new Date(photo.created_at).toLocaleDateString('zh-CN') }}
                      </p>
                      <n-tag size="small" type="default" :bordered="false" class="mt-2">
                        已删除
                      </n-tag>
                    </div>
                    <div class="flex gap-2">
                      <n-button size="small" tertiary type="success" @click="handleRestorePhoto(photo.id)">
                        恢复
                      </n-button>
                      <n-button size="small" tertiary type="error" @click="handlePermanentDeletePhoto(photo.id)">
                        永久删除
                      </n-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 小纸条回收站 -->
        <div v-if="deletedNotes.length > 0">
          <h3 class="text-lg font-bold text-pink-600 mb-3">小纸条</h3>
          <div class="space-y-3">
            <div
              v-for="note in deletedNotes"
              :key="note.id"
              class="glass-effect rounded-2xl p-5 shadow-pink-md opacity-50"
            >
              <div class="flex items-start gap-4">
                <div class="text-3xl grayscale">
                  {{ note.from_user_id === userId ? '💝' : '💌' }}
                </div>
                <div class="flex-1">
                  <div class="flex items-start justify-between mb-2">
                    <div>
                      <div class="flex items-center gap-2 mb-2">
                        <span class="font-bold text-pink-600 line-through">
                          {{ note.from_user_id === userId ? '我' : 'TA' }}
                        </span>
                        <span class="text-xs text-pink-400">
                          {{ new Date(note.created_at).toLocaleTimeString('zh-CN', {
                            hour: '2-digit',
                            minute: '2-digit',
                          }) }}
                        </span>
                      </div>
                      <p class="text-pink-600 line-through">{{ note.content }}</p>
                      <n-tag size="small" type="default" :bordered="false" class="mt-2">
                        已删除
                      </n-tag>
                    </div>
                    <div class="flex gap-2">
                      <n-button size="small" tertiary type="success" @click="handleRestoreNote(note.id)">
                        恢复
                      </n-button>
                      <n-button size="small" tertiary type="error" @click="handlePermanentDeleteNote(note.id)">
                        永久删除
                      </n-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 问答回收站 -->
        <div v-if="deletedQAs.length > 0">
          <h3 class="text-lg font-bold text-pink-600 mb-3">情侣问答</h3>
          <div class="space-y-3">
            <div
              v-for="qa in deletedQAs"
              :key="qa.id"
              class="glass-effect rounded-2xl p-5 shadow-pink-md opacity-50"
            >
              <div class="flex items-start gap-4">
                <div class="text-3xl grayscale">❓</div>
                <div class="flex-1">
                  <div class="flex items-start justify-between mb-2">
                    <div>
                      <h4 class="text-lg font-bold text-pink-600 line-through">{{ qa.question }}</h4>
                      <div class="space-y-1 text-sm mt-2">
                        <p class="text-pink-500 line-through">
                          💝 你: {{ (userId === 1 ? qa.answer_user1 : qa.answer_user2) || '未回答' }}
                        </p>
                        <p class="text-pink-500 line-through">
                          💌 TA: {{ (userId === 1 ? qa.answer_user2 : qa.answer_user1) || '未回答' }}
                        </p>
                      </div>
                      <n-tag size="small" type="default" :bordered="false" class="mt-2">
                        已删除
                      </n-tag>
                    </div>
                    <div class="flex gap-2">
                      <n-button size="small" tertiary type="success" @click="handleRestoreQA(qa.id)">
                        恢复
                      </n-button>
                      <n-button size="small" tertiary type="error" @click="handlePermanentDeleteQA(qa.id)">
                        永久删除
                      </n-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 书影音回收站 -->
        <div v-if="deletedMedias.length > 0">
          <h3 class="text-lg font-bold text-pink-600 mb-3">书影音</h3>
          <div class="space-y-3">
            <div
              v-for="media in deletedMedias"
              :key="media.id"
              class="glass-effect rounded-2xl p-5 shadow-pink-md opacity-50 flex items-start gap-4"
            >
              <div
                class="flex-shrink-0 w-16 h-16 bg-pink-100 rounded-xl flex items-center justify-center text-3xl grayscale"
              >
                {{ getMediaIcon(media.type) }}
              </div>
              <div class="flex-1">
                <div class="flex items-start justify-between mb-2">
                  <div>
                    <h4 class="font-bold text-pink-600 mb-1 line-through">{{ media.title }}</h4>
                    <p class="text-sm text-pink-400 mb-2">评分: {{ media.rating || '未评分' }}/10</p>
                    <div class="flex items-center gap-2">
                      <n-tag size="small" :bordered="false" type="info">
                        {{ media.creator_id === userId ? '我推荐' : 'TA推荐' }}
                      </n-tag>
                      <n-tag size="small" type="default" :bordered="false">
                        已删除
                      </n-tag>
                    </div>
                  </div>
                  <div class="flex gap-2">
                    <n-button size="small" tertiary type="success" @click="handleRestoreMedia(media.id)">
                      恢复
                    </n-button>
                    <n-button size="small" tertiary type="error" @click="handlePermanentDeleteMedia(media.id)">
                      永久删除
                    </n-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 写漂流瓶模态框 -->
    <n-modal v-model:show="showBottleModal">
      <div class="glass-effect rounded-3xl p-8 max-w-md w-full shadow-pink-xl">
        <h3 class="text-2xl font-bold text-pink-600 mb-6">写漂流瓶</h3>
        <n-form>
          <n-form-item label="心情">
            <n-input v-model:value="bottleForm.mood" placeholder="今天的心情如何？" />
          </n-form-item>
          <n-form-item label="内容">
            <n-input
              v-model:value="bottleForm.content"
              type="textarea"
              placeholder="写下你想说的话..."
              :rows="4"
            />
          </n-form-item>
          <n-form-item label="添加图片（可选）">
            <n-input v-model:value="bottleForm.imageUrl" placeholder="图片URL" />
          </n-form-item>
          <div class="flex gap-3">
            <n-button
              type="primary"
              size="large"
              block
              class="rounded-xl"
              @click="handleCreateBottle"
            >
              投入瓶中
            </n-button>
            <n-button size="large" block class="rounded-xl" @click="showBottleModal = false">
              取消
            </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>

    <!-- 上传照片模态框 -->
    <n-modal v-model:show="showPhotoModal">
      <div class="glass-effect rounded-3xl p-8 max-w-md w-full shadow-pink-xl">
        <h3 class="text-2xl font-bold text-pink-600 mb-6">上传照片</h3>
        <n-form>
          <n-form-item label="选择照片">
            <n-upload
              ref="uploadRef"
              :max="1"
              list-type="image-card"
              :default-upload="false"
              accept="image/png,image/jpeg,image/jpg,image/gif,image/webp"
              @change="handleFileChange"
            >
              <n-button>点击选择图片</n-button>
            </n-upload>
          </n-form-item>
          <n-form-item label="描述（可选）">
            <n-input v-model:value="photoForm.description" placeholder="为照片添加描述..." />
          </n-form-item>
          <div class="flex gap-3">
            <n-button
              type="primary"
              size="large"
              block
              class="rounded-xl"
              :loading="uploadLoading"
              :disabled="!photoForm.file"
              @click="handleUploadPhoto"
            >
              {{ uploadLoading ? '上传中...' : '上传' }}
            </n-button>
            <n-button size="large" block class="rounded-xl" @click="handleCancelUpload">
              取消
            </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>

    <!-- 添加问答模态框 -->
    <n-modal v-model:show="showQAModal">
      <div class="glass-effect rounded-3xl p-8 max-w-md w-full shadow-pink-xl">
        <h3 class="text-2xl font-bold text-pink-600 mb-6">添加问题</h3>
        <n-form>
          <n-form-item label="问题">
            <n-input v-model:value="qaForm.question" placeholder="输入你想问的问题..." />
          </n-form-item>
          <n-form-item label="你的答案（可选）">
            <n-input
              v-model:value="qaForm.myAnswer"
              type="textarea"
              placeholder="写下你的答案..."
              :rows="3"
            />
          </n-form-item>
          <div class="flex gap-3">
            <n-button type="primary" size="large" block class="rounded-xl" @click="handleCreateQA">
              添加
            </n-button>
            <n-button size="large" block class="rounded-xl" @click="showQAModal = false">
              取消
            </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>

    <!-- 添加书影音模态框 -->
    <n-modal v-model:show="showMediaModal">
      <div class="glass-effect rounded-3xl p-8 max-w-md w-full shadow-pink-xl">
        <h3 class="text-2xl font-bold text-pink-600 mb-6">添加推荐</h3>
        <n-form>
          <n-form-item label="类型">
            <n-select v-model:value="mediaForm.type" :options="mediaTypes" />
          </n-form-item>
          <n-form-item label="标题">
            <n-input v-model:value="mediaForm.title" placeholder="输入标题..." />
          </n-form-item>
          <n-form-item label="状态">
            <n-select
              v-model:value="mediaForm.status"
              :options="[
                { label: '想看', value: '想看' },
                { label: '已看', value: '已看' },
              ]"
            />
          </n-form-item>
          <n-form-item label="评分 (0-10)">
            <n-input-number
              v-model:value="mediaForm.rating"
              :min="0"
              :max="10"
              class="w-full"
            />
          </n-form-item>
          <n-form-item label="备注">
            <n-input
              v-model:value="mediaForm.note"
              type="textarea"
              placeholder="写下你的感受..."
              :rows="3"
            />
          </n-form-item>
          <div class="flex gap-3">
            <n-button type="primary" size="large" block class="rounded-xl" @click="handleCreateMedia">
              添加
            </n-button>
            <n-button size="large" block class="rounded-xl" @click="showMediaModal = false">
              取消
            </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useMessage, useDialog } from 'naive-ui'
import { storeToRefs } from 'pinia'
import { useAuthStore } from '@/stores/auth'
import * as bottleApi from '@/api/bottle'
import * as photoApi from '@/api/photo'
import * as noteApi from '@/api/note'
import * as checkinApi from '@/api/checkin'
import * as qaApi from '@/api/qa'
import * as mediaApi from '@/api/media'
import type { Bottle } from '@/types/bottle'
import type { Photo } from '@/types/photo'
import type { Note } from '@/types/note'
import type { DailyCheckin } from '@/types/checkin'
import type { QARecord } from '@/types/qa'
import type { MediaRecord } from '@/types/media'

const message = useMessage()
const dialog = useDialog()
const authStore = useAuthStore()
// 使用 storeToRefs 正确解包 Pinia store 的响应式属性
const { userInfo } = storeToRefs(authStore)
const userId = computed(() => {
  const user = userInfo.value
  return user ? user.id : 0
})

// Tab配置
const tabs = [
  { key: 'bottles', label: '漂流瓶', icon: '🎈' },
  { key: 'photos', label: '照片墙', icon: '📸' },
  { key: 'notes', label: '小纸条', icon: '💌' },
  { key: 'checkin', label: '打卡', icon: '📝' },
  { key: 'qa', label: '问答', icon: '❓' },
  { key: 'media', label: '书影音', icon: '📚' },
  { key: 'trash', label: '回收站', icon: '🗑️' },
]

const activeTab = ref('bottles')
const showBottleModal = ref(false)
const loading = ref(false)

// 漂流瓶数据
const bottlesData = ref<Bottle[]>([])
const bottles = computed(() => {
  if (!bottlesData.value) return []
  return bottlesData.value.map((bottle) => ({
    id: bottle.id,
    emoji: '🎈',
    author: bottle.creator_id === userId.value ? '我' : 'TA',
    date: new Date(bottle.created_at).toLocaleDateString('zh-CN'),
    content: bottle.content,
    image: bottle.images && bottle.images.length > 0 ? bottle.images[0] : null,
  }))
})

const bottleForm = ref({
  mood: '',
  content: '',
  imageUrl: '',
})

const loadBottles = async () => {
  try {
    const result = await bottleApi.getBottles()
    // 确保返回的是数组,如果不是则设为空数组
    bottlesData.value = Array.isArray(result) ? result : []
  } catch (error) {
    message.error('加载漂流瓶失败')
    bottlesData.value = []
  }
}

const handleCreateBottle = async () => {
  if (!bottleForm.value.content.trim()) {
    message.warning('请输入内容')
    return
  }

  // 检查用户是否已登录
  if (!userId.value || userId.value === 0) {
    message.error('请先登录')
    return
  }

  try {
    const images = bottleForm.value.imageUrl ? [bottleForm.value.imageUrl] : []
    await bottleApi.createBottle({
      content: `${bottleForm.value.mood ? bottleForm.value.mood + '：' : ''}${bottleForm.value.content}`,
      images,
      creator_id: userId.value,
    })
    message.success('漂流瓶投放成功 🎈')
    showBottleModal.value = false
    bottleForm.value = { mood: '', content: '', imageUrl: '' }
    await loadBottles()
  } catch (error) {
    message.error('投放失败')
  }
}

const randomBottle = async () => {
  try {
    const bottle = await bottleApi.getRandomBottle()
    message.info(
      `随机抽到了 ${new Date(bottle.created_at).toLocaleDateString('zh-CN')} 的漂流瓶`,
    )
  } catch (error) {
    message.error('获取随机漂流瓶失败')
  }
}

const handleDeleteBottle = (id: number) => {
  dialog.warning({
    title: '确认删除',
    content: '删除后可在回收站中恢复',
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await bottleApi.deleteBottle(id)
        message.success('漂流瓶已删除')
        await loadBottles()
        await loadDeletedBottles()
      } catch (error) {
        message.error('删除失败')
      }
    },
  })
}

// 照片墙数据
const showPhotoModal = ref(false)
const photosData = ref<Photo[]>([])
const photos = computed(() => {
  if (!photosData.value) return []
  return photosData.value.map((photo) => ({
    id: photo.id,
    title: photo.description || '美好回忆',
    date: new Date(photo.created_at).toLocaleDateString('zh-CN'),
    url: photo.url,
  }))
})

// 图片加载失败处理
const handleImageError = (e: Event) => {
  const img = e.target as HTMLImageElement
  img.src = ''
}

const photoForm = ref({
  file: null as File | null,
  description: '',
})

const uploadRef = ref()
const uploadLoading = ref(false)

const loadPhotos = async () => {
  try {
    const result = await photoApi.getPhotos()
    // 确保返回的是数组,如果不是则设为空数组
    photosData.value = Array.isArray(result) ? result : []
  } catch (error) {
    message.error('加载照片失败')
    photosData.value = []
  }
}

// 文件选择变化
const handleFileChange = (data: { fileList: any[] }) => {
  if (data.fileList.length > 0) {
    photoForm.value.file = data.fileList[0].file as File
  } else {
    photoForm.value.file = null
  }
}

// 取消上传
const handleCancelUpload = () => {
  showPhotoModal.value = false
  photoForm.value = { file: null, description: '' }
  if (uploadRef.value) {
    uploadRef.value.clear()
  }
}

// 上传照片
const handleUploadPhoto = async () => {
  if (!photoForm.value.file) {
    message.warning('请选择要上传的图片')
    return
  }

  // 检查用户是否已登录
  console.log('=== 上传照片调试信息 ===')
  console.log('authStore.userInfo:', authStore.userInfo)
  console.log('authStore.userInfo.value:', authStore.userInfo.value)
  console.log('userId.value:', userId.value)
  console.log('=====================')

  if (!userId.value || userId.value === 0) {
    message.error(`请先登录 (当前 userId: ${userId.value})`)
    return
  }

  uploadLoading.value = true
  try {
    await photoApi.uploadPhoto(photoForm.value.file, photoForm.value.description, userId.value)
    message.success('照片上传成功 📸')
    showPhotoModal.value = false
    photoForm.value = { file: null, description: '' }
    if (uploadRef.value) {
      uploadRef.value.clear()
    }
    await loadPhotos()
  } catch (error) {
    console.error('上传照片失败:', error)
    message.error('上传失败')
  } finally {
    uploadLoading.value = false
  }
}

const handleDeletePhoto = (id: number) => {
  dialog.warning({
    title: '确认删除',
    content: '确定要删除这张照片吗？',
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await photoApi.deletePhoto(id)
        message.success('照片已删除')
        await loadPhotos()
        await loadDeletedPhotos()
      } catch (error) {
        message.error('删除失败')
      }
    },
  })
}

// 小纸条数据
const newNote = ref('')
const notesData = ref<Note[]>([])
const notes = computed(() => {
  if (!notesData.value) return []
  return notesData.value.map((note) => ({
    id: note.id,
    fromMe: note.from_user_id === userId.value,
    author: note.from_user_id === userId.value ? '我' : 'TA',
    time: new Date(note.created_at).toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
    }),
    content: note.content,
  }))
})

const loadNotes = async () => {
  try {
    const result = await noteApi.getNotes()
    // 确保返回的是数组,如果不是则设为空数组
    notesData.value = Array.isArray(result) ? result : []
  } catch (error) {
    message.error('加载小纸条失败')
    notesData.value = []
  }
}

const addNote = async () => {
  if (!newNote.value.trim()) return

  // 检查用户是否已登录
  if (!userId.value || userId.value === 0) {
    message.error('请先登录')
    return
  }

  try {
    // 假设对方的 ID 是另一个用户（这里需要根据实际情况调整）
    const toUserId = userId.value === 1 ? 2 : 1
    await noteApi.createNote({
      content: newNote.value,
      from_user_id: userId.value,
      to_user_id: toUserId,
    })
    newNote.value = ''
    message.success('纸条发送成功 💌')
    await loadNotes()
  } catch (error) {
    message.error('发送纸条失败')
  }
}

const handleDeleteNote = (id: number) => {
  dialog.warning({
    title: '确认删除',
    content: '删除后可在回收站中恢复',
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await noteApi.deleteNote(id)
        message.success('小纸条已删除')
        await loadNotes()
        await loadDeletedNotes()
      } catch (error) {
        message.error('删除失败')
      }
    },
  })
}

// 打卡数据
const checkinsData = ref<DailyCheckin[]>([])
const todayCheckin = computed(() => {
  if (!checkinsData.value) {
    return { morning: false, evening: false }
  }
  const today = new Date().toISOString().split('T')[0]
  const todayCheckins = checkinsData.value.filter((c) => c.checkin_date.startsWith(today))
  return {
    morning: todayCheckins.some((c) => c.type === '早安'),
    evening: todayCheckins.some((c) => c.type === '晚安'),
  }
})

const checkinStats = computed(() => {
  if (!checkinsData.value || checkinsData.value.length === 0) {
    return { streak: 0, total: 0 }
  }
  // 计算连续打卡天数
  const dates = [
    ...new Set(checkinsData.value.map((c) => c.checkin_date.split('T')[0]).sort().reverse()),
  ]
  let streak = 0
  const today = new Date()
  for (let i = 0; i < dates.length; i++) {
    const date = new Date(dates[i])
    const diffDays = Math.floor((today.getTime() - date.getTime()) / (1000 * 60 * 60 * 24))
    if (diffDays === i) {
      streak++
    } else {
      break
    }
  }
  return {
    streak,
    total: checkinsData.value.length,
  }
})

const checkinHistory = computed(() => {
  if (!checkinsData.value || checkinsData.value.length === 0) {
    return []
  }
  const grouped = checkinsData.value.reduce(
    (acc, checkin) => {
      const date = checkin.checkin_date.split('T')[0]
      if (!acc[date]) {
        acc[date] = []
      }
      acc[date].push(checkin.type)
      return acc
    },
    {} as Record<string, string[]>,
  )

  return Object.entries(grouped)
    .map(([date, types]) => ({
      id: date,
      date: new Date(date).toLocaleDateString('zh-CN'),
      types: types.join(' · '),
      icon: '✓',
    }))
    .sort((a, b) => b.id.localeCompare(a.id))
    .slice(0, 10)
})

const loadCheckins = async () => {
  try {
    const result = await checkinApi.getUserCheckins(userId.value)
    // 确保返回的是数组,如果不是则设为空数组
    checkinsData.value = Array.isArray(result) ? result : []
  } catch (error) {
    message.error('加载打卡记录失败')
    checkinsData.value = []
  }
}

const handleCheckin = async (type: 'morning' | 'evening') => {
  if (todayCheckin.value[type]) {
    message.warning('今天已经打过卡啦 ~')
    return
  }

  // 检查用户是否已登录
  if (!userId.value || userId.value === 0) {
    message.error('请先登录')
    return
  }

  try {
    await checkinApi.createDailyCheckin({
      user_id: userId.value,
      type: type === 'morning' ? '早安' : '晚安',
    })
    message.success(type === 'morning' ? '早安打卡成功 🌅' : '晚安打卡成功 🌙')
    await loadCheckins()
  } catch (error) {
    message.error('打卡失败')
  }
}

// 问答数据
const showQAModal = ref(false)
const qaRecordsData = ref<QARecord[]>([])

const qaForm = ref({
  question: '',
  myAnswer: '',
})

const qaHistory = computed(() => {
  if (!qaRecordsData.value) return []
  return qaRecordsData.value.map((qa) => ({
    id: qa.id,
    question: qa.question,
    myAnswer: userId.value === 1 ? qa.answer_user1 : qa.answer_user2,
    taAnswer: userId.value === 1 ? qa.answer_user2 : qa.answer_user1,
    date: new Date(qa.question_date).toLocaleDateString('zh-CN'),
  }))
})

const loadQARecords = async () => {
  try {
    const result = await qaApi.getQARecords()
    // 确保返回的是数组,如果不是则设为空数组
    qaRecordsData.value = Array.isArray(result) ? result : []
  } catch (error) {
    message.error('加载问答记录失败')
    qaRecordsData.value = []
  }
}

const handleCreateQA = async () => {
  if (!qaForm.value.question.trim()) {
    message.warning('请输入问题')
    return
  }
  try {
    const data: any = {
      question: qaForm.value.question,
    }
    if (userId.value === 1) {
      data.answer_user1 = qaForm.value.myAnswer
    } else {
      data.answer_user2 = qaForm.value.myAnswer
    }
    await qaApi.createQARecord(data)
    message.success('问题添加成功 ❓')
    showQAModal.value = false
    qaForm.value = { question: '', myAnswer: '' }
    await loadQARecords()
  } catch (error) {
    message.error('添加失败')
  }
}

const handleDeleteQA = (id: number) => {
  dialog.warning({
    title: '确认删除',
    content: '确定要删除这个问题吗？',
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await qaApi.deleteQARecord(id)
        message.success('问题已删除')
        await loadQARecords()
        await loadDeletedQAs()
      } catch (error) {
        message.error('删除失败')
      }
    },
  })
}

// 书影音数据
const mediaTypes = [
  { key: '书', label: '书', icon: '📖', value: '书' },
  { key: '电影', label: '影', icon: '🎬', value: '电影' },
  { key: '音乐', label: '音', icon: '🎵', value: '音乐' },
]

const selectedMediaType = ref('电影')
const mediaRecordsData = ref<MediaRecord[]>([])

const getMediaIcon = (type: string) => {
  switch (type) {
    case '电影':
      return '🎬'
    case '书':
      return '📖'
    case '音乐':
      return '🎵'
    default:
      return '📚'
  }
}

const showMediaModal = ref(false)
const mediaForm = ref({
  type: '电影',
  title: '',
  status: '想看',
  rating: 0,
  note: '',
})

const filteredMedia = computed(() => {
  if (!mediaRecordsData.value) return []
  return mediaRecordsData.value
    .filter((item) => item.type === selectedMediaType.value)
    .map((item) => ({
      id: item.id,
      type: item.type,
      icon: getMediaIcon(item.type),
      title: item.title,
      rating: item.rating,
      fromMe: item.creator_id === userId.value,
      completed: item.status === '已看',
    }))
})

const loadMediaRecords = async () => {
  try {
    const result = await mediaApi.getMediaRecords()
    // 确保返回的是数组,如果不是则设为空数组
    mediaRecordsData.value = Array.isArray(result) ? result : []
  } catch (error) {
    message.error('加载书影音记录失败')
    mediaRecordsData.value = []
  }
}

const handleCreateMedia = async () => {
  if (!mediaForm.value.title.trim()) {
    message.warning('请输入标题')
    return
  }

  // 检查用户是否已登录
  if (!userId.value || userId.value === 0) {
    message.error('请先登录')
    return
  }

  try {
    await mediaApi.createMediaRecord({
      title: mediaForm.value.title,
      type: mediaForm.value.type,
      status: mediaForm.value.status,
      rating: mediaForm.value.rating,
      note: mediaForm.value.note,
      creator_id: userId.value,
    })
    message.success('推荐添加成功 📚')
    showMediaModal.value = false
    mediaForm.value = { type: '电影', title: '', status: '想看', rating: 0, note: '' }
    await loadMediaRecords()
  } catch (error) {
    message.error('添加失败')
  }
}

const handleDeleteMedia = (id: number) => {
  dialog.warning({
    title: '确认删除',
    content: '确定要删除这条记录吗？',
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await mediaApi.deleteMediaRecord(id)
        message.success('记录已删除')
        await loadMediaRecords()
        await loadDeletedMedias()
      } catch (error) {
        message.error('删除失败')
      }
    },
  })
}

// 回收站数据
const deletedBottles = ref<Bottle[]>([])
const deletedPhotos = ref<Photo[]>([])
const deletedNotes = ref<Note[]>([])
const deletedQAs = ref<QARecord[]>([])
const deletedMedias = ref<MediaRecord[]>([])

// 加载已删除数据
const loadDeletedBottles = async () => {
  try {
    const result = await bottleApi.getDeletedBottles()
    deletedBottles.value = Array.isArray(result) ? result : []
  } catch (error) {
    console.error('加载已删除漂流瓶失败', error)
    deletedBottles.value = []
  }
}

const loadDeletedPhotos = async () => {
  try {
    const result = await photoApi.getDeletedPhotos()
    deletedPhotos.value = Array.isArray(result) ? result : []
  } catch (error) {
    console.error('加载已删除照片失败', error)
    deletedPhotos.value = []
  }
}

const loadDeletedNotes = async () => {
  try {
    const result = await noteApi.getDeletedNotes()
    deletedNotes.value = Array.isArray(result) ? result : []
  } catch (error) {
    console.error('加载已删除小纸条失败', error)
    deletedNotes.value = []
  }
}

const loadDeletedQAs = async () => {
  try {
    const result = await qaApi.getDeletedQARecords()
    deletedQAs.value = Array.isArray(result) ? result : []
  } catch (error) {
    console.error('加载已删除问答失败', error)
    deletedQAs.value = []
  }
}

const loadDeletedMedias = async () => {
  try {
    const result = await mediaApi.getDeletedMediaRecords()
    deletedMedias.value = Array.isArray(result) ? result : []
  } catch (error) {
    console.error('加载已删除书影音失败', error)
    deletedMedias.value = []
  }
}

// 恢复操作
const handleRestoreBottle = (id: number) => {
  dialog.info({
    title: '恢复漂流瓶',
    content: '确定要恢复这个漂流瓶吗？',
    positiveText: '恢复',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await bottleApi.restoreBottle(id)
        message.success('漂流瓶已恢复')
        await loadBottles()
        await loadDeletedBottles()
      } catch (error) {
        message.error('恢复失败')
      }
    },
  })
}

const handleRestorePhoto = (id: number) => {
  dialog.info({
    title: '恢复照片',
    content: '确定要恢复这张照片吗？',
    positiveText: '恢复',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await photoApi.restorePhoto(id)
        message.success('照片已恢复')
        await loadPhotos()
        await loadDeletedPhotos()
      } catch (error) {
        message.error('恢复失败')
      }
    },
  })
}

const handleRestoreNote = (id: number) => {
  dialog.info({
    title: '恢复小纸条',
    content: '确定要恢复这条小纸条吗？',
    positiveText: '恢复',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await noteApi.restoreNote(id)
        message.success('小纸条已恢复')
        await loadNotes()
        await loadDeletedNotes()
      } catch (error) {
        message.error('恢复失败')
      }
    },
  })
}

const handleRestoreQA = (id: number) => {
  dialog.info({
    title: '恢复问答',
    content: '确定要恢复这个问题吗？',
    positiveText: '恢复',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await qaApi.restoreQARecord(id)
        message.success('问答已恢复')
        await loadQARecords()
        await loadDeletedQAs()
      } catch (error) {
        message.error('恢复失败')
      }
    },
  })
}

const handleRestoreMedia = (id: number) => {
  dialog.info({
    title: '恢复记录',
    content: '确定要恢复这条记录吗？',
    positiveText: '恢复',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await mediaApi.restoreMediaRecord(id)
        message.success('记录已恢复')
        await loadMediaRecords()
        await loadDeletedMedias()
      } catch (error) {
        message.error('恢复失败')
      }
    },
  })
}

// 永久删除操作
const handlePermanentDeleteBottle = (id: number) => {
  dialog.error({
    title: '永久删除',
    content: '确定要永久删除这个漂流瓶吗？此操作不可恢复！',
    positiveText: '确认删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await bottleApi.permanentDeleteBottle(id)
        message.success('漂流瓶已永久删除')
        await loadDeletedBottles()
      } catch (error) {
        message.error('删除失败')
      }
    },
  })
}

const handlePermanentDeletePhoto = (id: number) => {
  dialog.error({
    title: '永久删除',
    content: '确定要永久删除这张照片吗？此操作不可恢复！',
    positiveText: '确认删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await photoApi.permanentDeletePhoto(id)
        message.success('照片已永久删除')
        await loadDeletedPhotos()
      } catch (error) {
        message.error('删除失败')
      }
    },
  })
}

const handlePermanentDeleteNote = (id: number) => {
  dialog.error({
    title: '永久删除',
    content: '确定要永久删除这条小纸条吗？此操作不可恢复！',
    positiveText: '确认删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await noteApi.permanentDeleteNote(id)
        message.success('小纸条已永久删除')
        await loadDeletedNotes()
      } catch (error) {
        message.error('删除失败')
      }
    },
  })
}

const handlePermanentDeleteQA = (id: number) => {
  dialog.error({
    title: '永久删除',
    content: '确定要永久删除这个问题吗？此操作不可恢复！',
    positiveText: '确认删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await qaApi.permanentDeleteQARecord(id)
        message.success('问答已永久删除')
        await loadDeletedQAs()
      } catch (error) {
        message.error('删除失败')
      }
    },
  })
}

const handlePermanentDeleteMedia = (id: number) => {
  dialog.error({
    title: '永久删除',
    content: '确定要永久删除这条记录吗？此操作不可恢复！',
    positiveText: '确认删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await mediaApi.permanentDeleteMediaRecord(id)
        message.success('记录已永久删除')
        await loadDeletedMedias()
      } catch (error) {
        message.error('删除失败')
      }
    },
  })
}

// 页面加载
onMounted(async () => {
  loading.value = true
  try {
    await Promise.all([
      loadBottles(),
      loadPhotos(),
      loadNotes(),
      loadCheckins(),
      loadQARecords(),
      loadMediaRecords(),
      loadDeletedBottles(),
      loadDeletedPhotos(),
      loadDeletedNotes(),
      loadDeletedQAs(),
      loadDeletedMedias(),
    ])
  } finally {
    loading.value = false
  }
})
</script>
